<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Phira 服务器控制面板</title>
    <style>
        /* 基础样式与重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            color: #ffffff;
            background-color: #0d0d0d;
            min-height: 100vh;
            overflow-x: hidden;
            position: relative;
        }

        /* 背景图样式 */
        .parallax-bg {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), 
                              url('https://webstatic.cn-nb1.rains3.com/5712%C3%973360.jpeg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            z-index: 0;
        }

        /* 头部导航栏 */
        header {
            position: fixed;
            top: 0;
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 1.5rem;
            backdrop-filter: blur(12px);
            background: rgba(0, 0, 0, 0.4);
            z-index: 1000;
            box-sizing: border-box;
        }
        
        .logo-nav-container {
            display: flex;
            align-items: center;
            flex: 1;
        }
        
        #logo-img {
            height: 32px;
            margin-right: 1.2rem;
        }
        
        .nav-links {
            display: flex;
        }
        
        .nav-links a {
            color: #eee;
            margin-right: 1.2rem;
            text-decoration: none;
            transition: 0.3s;
            font-size: 0.95rem;
        }
        
        .nav-links a:hover {
            color: #fff;
            text-shadow: 0 0 4px #fff;
        }
        
        .user-section {
            display: flex;
            justify-content: flex-end;
            flex: 1;
        }
        
        .glass-button {
            display: flex;
            align-items: center;
            padding: 0.4rem 1rem;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 999px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 100px;
        }
        
        .glass-button:hover {
            background: rgba(255, 255, 255, 0.15);
            transform: scale(1.05);
        }
        
        .user-info {
            display: flex;
            align-items: center;
            position: relative;
            cursor: pointer;
            width: 100%;
        }
        
        .username {
            margin-right: 0.8rem;
            font-size: 0.95rem;
            color: #eee;
            max-width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .user-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            object-fit: cover;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .dropdown-content {
            position: absolute;
            top: 100%;
            right: 0;
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(12px);
            border-radius: 8px;
            padding: 0.8rem;
            min-width: 160px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.5);
            z-index: 1001;
            opacity: 0;
            visibility: hidden;
            transform: translateY(10px);
            transition: all 0.3s ease;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .dropdown-content.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }
        
        .dropdown-content span {
            display: block;
            padding: 0.3rem 0.5rem;
            font-weight: bold;
            color: #a1e5ef; /* 修改为冰蓝色 */
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 0.5rem;
        }
        
        .dropdown-content a {
            display: block;
            padding: 0.5rem;
            color: #eee;
            text-decoration: none;
            border-radius: 4px;
            transition: all 0.3s ease;
        }
        
        .dropdown-content a:hover {
            background: rgba(255, 255, 255, 0.1);
            color: #fff;
        }

        /* 主内容区 */
        main {
            position: relative;
            z-index: 2;
            padding-top: 100px;
            display: flex;
            flex-direction: column;
            align-items: center;
            min-height: 100vh;
            padding-bottom: 50px;
        }

        /* 3D毛玻璃卡片 */
        .admin-container {
            transform-style: preserve-3d;
            transform: translateZ(20px);
            transition: transform 0.3s ease;
            animation: gentleSway 8s infinite ease-in-out;
            width: 95%;
            max-width: 1200px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 16px;
            backdrop-filter: blur(12px);
            padding: 2rem;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
            margin: 1rem;
        }

        @keyframes gentleSway {
            0%, 100% { transform: translateZ(20px) rotateX(0.5deg) rotateY(0.5deg); }
            25% { transform: translateZ(20px) rotateX(-0.5deg) rotateY(-1deg); }
            50% { transform: translateZ(20px) rotateX(0.5deg) rotateY(1deg); }
            75% { transform: translateZ(20px) rotateX(-0.5deg) rotateY(0.5deg); }
        }

        .admin-container.tilting {
            animation: none;
            transition: transform 0.1s linear;
        }
        
        .admin-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            padding-bottom: 1.5rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .admin-title {
            font-size: 2rem;
            color: #a1e5ef; /* 修改为冰蓝色 */
        }

        /* 卡片容器 */
        .cards-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
        }

        /* 状态卡片 */
        .glass-card {
            backdrop-filter: blur(12px);
            background: rgba(30, 30, 42, 0.25);
            border-radius: 16px;
            padding: 1.5rem;
            border: 1px solid rgba(255, 255, 255, 0.15);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            transition: transform 0.3s ease;
        }

        .glass-card:hover {
            transform: translateY(-5px);
        }

        .glass-card h1, .glass-card h2 {
            margin-bottom: 1.2rem;
            font-weight: 500;
        }

        .status-card {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .status-dot {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background: #666;
            display: inline-block;
            margin-right: 10px;
        }

        #serverStatusContainer {
            display: flex;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        /* 控制按钮 */
        .control-buttons {
            display: flex;
            justify-content: space-between;
            gap: 1rem;
        }

        .glass-button-control {
            padding: 0.8rem 1.5rem;
            backdrop-filter: blur(5px);
            background: rgba(80, 90, 200, 0.25);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            min-width: 100px;
            text-align: center;
        }

        .glass-button-control:hover {
            background: rgba(100, 110, 220, 0.35);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        /* 自定义命令 */
        .cmd-input {
            display: flex;
            gap: 10px;
        }

        #customCommand {
            flex: 1;
            padding: 0.8rem;
            background: rgba(30, 30, 42, 0.4);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            color: white;
        }

        #customCommand::placeholder {
            color: rgba(255, 255, 255, 0.5);
        }

        /* 输出卡片 */
        .output-card {
            grid-column: 1 / -1;
        }

        #commandOutput {
            min-height: 200px;
            max-height: 400px;
            overflow: auto;
            padding: 1rem;
            background: rgba(20, 20, 30, 0.4);
            border-radius: 8px;
            font-family: 'Consolas', 'Courier New', monospace;
            white-space: pre-wrap;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        /* 状态颜色 */
        .status-online {
            background-color: #4caf50;
        }
        .status-offline {
            background-color: #f44336;
        }
        .status-loading {
            background-color: #ffc107;
        }

        /* 消息提示 */
        .message {
            padding: 0.8rem;
            border-radius: 8px;
            margin: 1rem 0;
            text-align: center;
            display: none;
            backdrop-filter: blur(6px);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .message-success {
            background: rgba(0, 200, 0, 0.2);
            color: #0f0;
        }
        
        .message-error {
            background: rgba(200, 0, 0, 0.2);
            color: #f33;
        }

        /* 用户管理部分样式 */
        .admin-tabs {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            width: 100%;
            max-width: 1200px;
        }
        
        .tab-button {
            padding: 0.8rem 1.5rem;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: #eee;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 1rem;
        }
        
        .tab-button.active {
            background: rgba(161, 229, 239, 0.25); /* 冰蓝色 */
            border-color: rgba(161, 229, 239, 0.5); /* 冰蓝色 */
            color: #fff;
        }
        
        .tab-button:hover {
            background: rgba(255, 255, 255, 0.15);
        }
        
        .tab-content {
            display: none;
            width: 95%;
            max-width: 1200px;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .user-count {
            background: rgba(161, 229, 239, 0.2); /* 冰蓝色 */
            color: #a1e5ef; /* 冰蓝色 */
            padding: 0.5rem 1rem;
            border-radius: 999px;
            font-weight: bold;
        }
        
        .filters {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }
        
        .filter-input {
            flex: 1;
            min-width: 250px;
            padding: 0.8rem 1rem;
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            color: #fff;
            font-size: 1rem;
            outline: none;
        }
        
        .filter-input:focus {
            border-color: rgba(255, 255, 255, 0.4);
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
        }
        
        .users-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 2rem;
        }
        
        .users-table th {
            text-align: left;
            padding: 1rem;
            background: rgba(161, 229, 239, 0.1); /* 冰蓝色 */
            color: #a1e5ef; /* 冰蓝色 */
            font-weight: 500;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .users-table td {
            padding: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .user-row:hover {
            background: rgba(255, 255, 255, 0.03);
        }
        
        .user-avatar-small {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .user-select {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }
        
        .badge {
            display: inline-block;
            padding: 0.3rem 0.8rem;
            border-radius: 999px;
            font-size: 0.85rem;
            margin-right: 0.5rem;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .badge-admin {
            background: rgba(161, 229, 239, 0.2); /* 冰蓝色 */
            color: #a1e5ef; /* 冰蓝色 */
        }
        
        .badge-dev {
            background: rgba(0, 204, 255, 0.2);
            color: #00ccff;
        }
        
        .actions-cell {
            display: flex;
            gap: 0.5rem;
        }
        
        .action-btn {
            padding: 0.4rem 0.8rem;
            border-radius: 6px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .action-btn:hover {
            background: rgba(255, 255, 255, 0.15);
        }
        
        .btn-edit {
            background: rgba(0, 150, 255, 0.2);
            color: #0096ff;
        }
        
        .batch-actions {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
            flex-wrap: wrap;
        }
        
        .batch-form {
            display: flex;
            gap: 1rem;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .batch-label {
            color: #ddd;
            font-size: 0.9rem;
        }
        
        .batch-select {
            padding: 0.6rem 1rem;
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            color: #fff;
            min-width: 150px;
        }
        
        /* 模态框样式 */
        .modal {
            position: fixed;
            top: 0; left: 0;
            width: 100vw; height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background: rgba(0,0,0,0.7);
            backdrop-filter: blur(10px);
            z-index: 9999;
            display: none;
        }
        
        .modal-content {
            background: rgba(30, 30, 40, 0.9);
            padding: 2rem;
            border-radius: 16px;
            color: #fff;
            backdrop-filter: blur(20px);
            max-width: 500px;
            width: 90%;
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }
        
        .modal-title {
            font-size: 1.5rem;
            color: #a1e5ef; /* 冰蓝色 */
            margin: 0;
        }
        
        .close-modal {
            background: none;
            border: none;
            color: #aaa;
            font-size: 1.5rem;
            cursor: pointer;
            transition: color 0.3s;
        }
        
        .close-modal:hover {
            color: #fff;
        }
        
        .modal-body {
            margin-bottom: 1.5rem;
        }
        
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
        }
        
        .password-display {
            background: rgba(0, 0, 0, 0.3);
            padding: 0.8rem;
            border-radius: 8px;
            font-family: monospace;
            word-break: break-all;
            margin: 0.5rem 0;
        }
        
        .reveal-btn {
            background: rgba(161, 229, 239, 0.2); /* 冰蓝色 */
            color: #a1e5ef; /* 冰蓝色 */
            border: none;
            padding: 0.3rem 0.8rem;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            header {
                flex-wrap: wrap;
            }
            .logo-nav-container {
                flex: 0 0 100%;
                margin-bottom: 0.5rem;
            }
            .user-section {
                flex: 0 0 100%;
                justify-content: flex-end;
            }
            .nav-links a {
                margin-right: 1rem;
            }
            .username {
                max-width: 80px;
            }
            .control-buttons {
                flex-direction: column;
            }
            .cards-container {
                grid-template-columns: 1fr;
            }
            .filters {
                flex-direction: column;
            }
            .users-table {
                display: block;
                overflow-x: auto;
            }
            .batch-form {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="parallax-bg"></div>
    
    <header>
        <div class="logo-nav-container">
            
            <div class="nav-links">
                <a href="index.html">主页</a>
                <a href="rooms.html">房间列表</a>
                <a href="account.html">账号管理</a>
                <a href="admin.html" style="color: #a1e5ef;">管理员控制台</a> <!-- 修改为冰蓝色 -->
            </div>
        </div>
        
        <div class="user-section">
            <div id="avatar-container" class="glass-button">
                <div class="user-info" onclick="toggleDropdown()">
                    <span class="username" id="username-display"></span>
                    
                </div>
                <div class="dropdown-content" id="user-dropdown">
                    <span id="dropdown-username"></span>
                    <a id="phira-profile-link" target="_blank">我的Phira账户</a>
                    <a href="account.html">账号管理</a>
                    <a href="javascript:void(0)" onclick="logout()">退出登录</a>
                </div>
            </div>
        </div>
    </header>
    
    <main>
        <div class="admin-tabs">
            <button class="tab-button active" data-tab="server-control">服务器控制</button>
            <button class="tab-button" data-tab="user-management">用户管理</button>
        </div>
        
        <!-- 服务器控制面板 -->
        <div id="server-control" class="tab-content active">
            <div class="admin-container">
                <div class="admin-header">
                    <h1 class="admin-title">服务器控制面板</h1>
                </div>
                
                <div id="admin-message" class="message"></div>
                
                <div class="cards-container">
                    <!-- 服务器状态卡片 -->
                    <div class="glass-card status-card">
                        <h2>服务器状态</h2>
                        <div id="serverStatusContainer">
                            <div class="status-dot" id="serverStatusDot"></div>
                            <span id="serverStatus">检测中...</span>
                        </div>
                        <div style="display: flex; justify-content: center; width: 100%;">
                            <button id="refreshStatus" class="glass-button-control">刷新状态</button>
                        </div>
                    </div>
                    
                    <!-- API状态卡片 -->
                    <div class="glass-card status-card">
                        <h2>API状态</h2>
                        <div id="apiStatusContainer">
                            <div class="status-dot" id="apiStatusDot"></div>
                            <span id="apiStatus">检测中...</span>
                        </div>
                    </div>
                    
                    <!-- 服务控制卡片 -->
                    <div class="glass-card control-card">
                        <h2>服务控制</h2>
                        <div class="control-buttons">
                            <button id="startServer" class="glass-button-control">启动</button>
                            <button id="restartServer" class="glass-button-control">重启</button>
                            <button id="stopServer" class="glass-button-control">关闭</button>
                        </div>
                    </div>
                    
                    <!-- 自定义命令卡片 -->
                    <div class="glass-card custom-cmd-card">
                        <h2>自定义命令</h2>
                        <div class="cmd-input">
                            <input type="text" id="customCommand" placeholder="输入命令...">
                            <button id="executeCmd" class="glass-button-control">执行</button>
                        </div>
                    </div>
                    
                    <!-- 命令输出卡片 -->
                    <div class="glass-card output-card">
                        <h2>命令执行结果</h2>
                        <pre id="commandOutput">等待命令执行...</pre>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 用户管理面板 -->
        <div id="user-management" class="tab-content">
            <div class="admin-container">
                <div class="admin-header">
                    <h1 class="admin-title">用户管理</h1>
                    <div class="user-count">用户总数: <span id="total-users">0</span></div>
                </div>
                
                <div class="filters">
                    <input type="text" class="filter-input" id="search-name" placeholder="搜索用户名..." />
                    <input type="text" class="filter-input" id="search-phira" placeholder="搜索Phira ID..." />
                    <select class="filter-input" id="filter-admin">
                        <option value="all">所有管理员状态</option>
                        <option value="yes">管理员</option>
                        <option value="no">非管理员</option>
                    </select>
                    <select class="filter-input" id="filter-dev">
                        <option value="all">所有开发者状态</option>
                        <option value="yes">开发者</option>
                        <option value="no">非开发者</option>
                    </select>
                </div>
                
                <div class="batch-actions">
                    <div class="batch-form">
                        <span class="batch-label">批量操作:</span>
                        <select class="batch-select" id="batch-action">
                            <option value="set_admin">设为管理员</option>
                            <option value="remove_admin">取消管理员</option>
                            <option value="set_dev">设为开发者</option>
                            <option value="remove_dev">取消开发者</option>
                        </select>
                        <button class="glass-button-control" onclick="applyBatchAction()">应用</button>
                        <button class="glass-button-control" onclick="selectAllUsers()">全选</button>
                        <button class="glass-button-control" onclick="deselectAllUsers()">取消全选</button>
                    </div>
                </div>
                
                <div id="user-message" class="message"></div>
                
                <div class="table-container">
                    <table class="users-table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select-all" class="user-select" /></th>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>头像</th>
                                <th>Phira ID</th>
                                <th>Phira 用户名</th>
                                <th>RKS</th>
                                <th>权限</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="users-table-body">
                            <!-- 用户数据将通过JavaScript填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>
    
    <!-- 编辑用户模态框 -->
    <div id="edit-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">编辑用户信息</h3>
                <button class="close-modal" onclick="closeEditModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="edit-message" class="message"></div>
                
                <input type="hidden" id="edit-user-id" />
                
                <div class="form-group">
                    <label class="form-label">用户名</label>
                    <input type="text" class="form-input" id="edit-username" />
                </div>
                
                <div class="form-group">
                    <label class="form-label">密码</label>
                    <div class="password-display" id="password-display">************</div>
                    <button class="reveal-btn" onclick="togglePasswordDisplay()">显示/隐藏密码</button>
                    <input type="password" class="form-input" id="edit-password" placeholder="输入新密码" style="margin-top: 0.5rem;" />
                </div>
                
                <div class="form-group">
                    <label class="form-label">Phira ID</label>
                    <input type="text" class="form-input" id="edit-phira-id" />
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <label class="form-label">管理员状态</label>
                        <select class="form-input" id="edit-admin">
                            <option value="no">否</option>
                            <option value="yes">是</option>
                        </select>
                    </div>
                    <div class="form-col">
                        <label class="form-label">开发者权限</label>
                        <select class="form-input" id="edit-dev">
                            <option value="no">否</option>
                            <option value="yes">是</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="glass-button-control" onclick="closeEditModal()">取消</button>
                <button class="glass-button-control" onclick="saveUserChanges()">保存更改</button>
            </div>
        </div>
    </div>
    
    <!-- 管理员密码模态框 -->
    <div id="admin-password-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">管理员验证</h3>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">请输入管理员密码</label>
                    <input type="password" class="form-input" id="admin-password-input" placeholder="管理员密码" />
                </div>
                <div id="admin-password-message" class="message"></div>
            </div>
            <div class="modal-footer">
                <button class="glass-button-control" onclick="closeAdminPasswordModal()">取消</button>
                <button class="glass-button-control" onclick="verifyAdminPassword()">验证</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentUser = null;
        const API_BASE_URL = 'https://phira.htadiy.cc/postadmin';
        const API_PWD1 = 'nb3502022';
        const API_PWD2 = '2022350';
        const API_PWD3 = 'nb3502022outlookcom';
        
        // 用户管理相关全局变量
        let allUsers = [];
        let adminPassword = '';
        let isSuperAdmin = false;
        
        // 状态颜色常量
        const STATUS_COLORS = {
            online: '#4caf50',
            offline: '#f44336',
            loading: '#ffc107',
            unknown: '#9e9e9e'
        };
        
        // 脚本命令配置
        const SERVER_COMMANDS = {
            start: 'bash /root/start.sh',
            restart: 'bash /root/stop.sh && bash /root/start.sh',
            stop: 'bash /root/stop.sh',
            check: 'bash /root/check.sh'
        };
        
        // 页面加载时检查登录状态和管理员权限
        document.addEventListener('DOMContentLoaded', () => {
            const savedUser = localStorage.getItem('user');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
                
                // 检查是否为管理员
                if (currentUser.admin !== "yes") {
                    showAdminMessage('您不是管理员，无法访问此页面', false);
                    setTimeout(() => {
                        window.location.href = 'index.html';
                    }, 2000);
                    return;
                }
                
                updateUserDisplay();
                checkAllStatus();
                
                // 设置选项卡切换事件
                document.querySelectorAll('.tab-button').forEach(button => {
                    button.addEventListener('click', () => {
                        // 移除所有活动状态
                        document.querySelectorAll('.tab-button').forEach(btn => {
                            btn.classList.remove('active');
                        });
                        document.querySelectorAll('.tab-content').forEach(content => {
                            content.classList.remove('active');
                        });
                        
                        // 设置当前活动状态
                        button.classList.add('active');
                        const tabId = button.getAttribute('data-tab');
                        document.getElementById(tabId).classList.add('active');
                        
                        // 如果是用户管理选项卡且还未加载过用户数据，则加载
                        if (tabId === 'user-management' && allUsers.length === 0) {
                            showAdminPasswordModal();
                        }
                    });
                });
            } else {
                // 未登录，重定向到登录页
                showAdminMessage('请先登录', false);
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1500);
            }
            
            // 绑定事件监听器
            document.getElementById('refreshStatus').addEventListener('click', checkAllStatus);
            document.getElementById('startServer').addEventListener('click', () => executeServerCommand('start'));
            document.getElementById('restartServer').addEventListener('click', () => executeServerCommand('restart'));
            document.getElementById('stopServer').addEventListener('click', () => executeServerCommand('stop'));
            document.getElementById('executeCmd').addEventListener('click', executeCustomCommand);
            
            // 按Enter键执行自定义命令
            document.getElementById('customCommand').addEventListener('keyup', (e) => {
                if (e.key === 'Enter') executeCustomCommand();
            });
        });
        
        // 更新用户显示
        function updateUserDisplay() {
            if (currentUser) {
                document.getElementById('username-display').textContent = currentUser.name;
                document.getElementById('user-avatar').src = currentUser.image_url || 'https://phira.moe/assets/user-6212ee95.png';
                document.getElementById('dropdown-username').textContent = currentUser.name;
                document.getElementById('phira-profile-link').href = `https://phira.5wyxi.com/user/${currentUser.phira_id}`;
            }
        }
        
        // 切换下拉菜单
        function toggleDropdown() {
            const dropdown = document.getElementById('user-dropdown');
            if (dropdown) {
                dropdown.classList.toggle('show');
            }
        }
        
        // 退出登录
        function logout() {
            localStorage.removeItem('user');
            window.location.href = 'index.html';
        }
        
        // 显示管理员消息
        function showAdminMessage(message, isSuccess) {
            const messageElement = document.getElementById('admin-message');
            messageElement.textContent = message;
            messageElement.className = `message ${isSuccess ? 'message-success' : 'message-error'}`;
            messageElement.style.display = 'block';
            
            // 5秒后隐藏消息
            setTimeout(() => {
                messageElement.style.display = 'none';
            }, 5000);
        }
        
        // 检查所有状态
        function checkAllStatus() {
            checkApiStatus();
            checkServerStatus();
        }
        
        // 检查API状态（service.htadiy.cc/rooms）
        function checkApiStatus() {
            updateApiStatus('检测中...', 'loading');
            
            fetch('https://phira.htadiy.cc/roomsjson', {
                method: 'GET',
                cache: 'no-store'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('API响应错误');
                }
                return response.json();
            })
            .then(data => {
                // 检查返回内容是否有数据
                if (Array.isArray(data) && data.length > 0) {
                    updateApiStatus('在线', 'online');
                } else {
                    updateApiStatus('在线', 'online');
                }
            })
            .catch(() => {
                updateApiStatus('离线', 'offline');
            });
        }
        
        // 更新API状态显示
        function updateApiStatus(text, status) {
            const apiStatusText = document.getElementById('apiStatus');
            const apiStatusDot = document.getElementById('apiStatusDot');
            
            apiStatusText.textContent = text;
            apiStatusDot.style.backgroundColor = STATUS_COLORS[status] || STATUS_COLORS.unknown;
        }
        
        // 检查服务器状态（使用bash /root/check.sh命令）
        function checkServerStatus() {
            updateServerStatus('检测中...', 'loading');
            
            // 发送检查命令到API
            sendAuthenticatedCommand('custom', SERVER_COMMANDS.check)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('服务器响应错误');
                    }
                    return response.json(); // 尝试解析为JSON
                })
                .then(data => {
                    // 检查返回结果中是否有错误
                    if (data.status === "success") {
                        updateServerStatus('运行中', 'online');
                    } else {
                        updateServerStatus('已停止', 'offline');
                    }
                })
                .catch(() => {
                    // 所有错误情况都视为服务器停止
                    updateServerStatus('已停止', 'offline');
                });
        }
        
        // 更新服务器状态显示
        function updateServerStatus(text, status) {
            const serverStatusText = document.getElementById('serverStatus');
            const serverStatusDot = document.getElementById('serverStatusDot');
            
            serverStatusText.textContent = text;
            serverStatusDot.style.backgroundColor = STATUS_COLORS[status] || STATUS_COLORS.unknown;
        }
        
        // 创建并发送带身份验证参数的请求
        function sendAuthenticatedCommand(command, customCmd = null) {
            const params = new URLSearchParams();
            params.append('pwd1', API_PWD1);
            params.append('pwd2', API_PWD2);
            params.append('pwd3', API_PWD3);
            
            if (customCmd) {
                params.append('cmd', 'custom');
                params.append('custom_cmd', customCmd);
            } else {
                params.append('cmd', command);
            }
            
            return fetch(`${API_BASE_URL}/execute`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: params
            });
        }
        
        // 执行服务器控制命令（使用bash脚本）
        function executeServerCommand(commandType) {
            if (!SERVER_COMMANDS[commandType]) return;
            
            const commandOutput = document.getElementById('commandOutput');
            commandOutput.textContent = '执行中...';
            
            // 直接发送自定义的bash脚本命令
            sendAuthenticatedCommand('custom', SERVER_COMMANDS[commandType])
                .then(response => {
                    if (response.ok) {
                        return response.text();
                    } else {
                        throw new Error('服务器响应错误');
                    }
                })
                .then(data => {
                    commandOutput.textContent = data;
                    // 执行完成后重新检查状态
                    setTimeout(() => {
                        checkServerStatus();
                    }, 2000);
                })
                .catch(error => {
                    commandOutput.textContent = `错误: ${error.message || '执行失败'}`;
                });
        }
        
        // 执行自定义命令
        function executeCustomCommand() {
            const command = document.getElementById('customCommand').value.trim();
            const commandOutput = document.getElementById('commandOutput');
            
            if (!command) {
                commandOutput.textContent = '错误：请输入命令';
                return;
            }
            
            commandOutput.textContent = '执行中...';
            
            // 直接发送自定义命令
            sendAuthenticatedCommand('custom', command)
                .then(response => {
                    if (response.ok) {
                        return response.text();
                    } else {
                        throw new Error('服务器响应错误');
                    }
                })
                .then(data => {
                    commandOutput.textContent = data;
                    document.getElementById('customCommand').value = '';
                })
                .catch(error => {
                    commandOutput.textContent = `错误: ${error.message || '执行失败'}`;
                });
        }
        
        // ========= 用户管理功能 =========
        
        // 显示管理员密码验证模态框
        function showAdminPasswordModal() {
            document.getElementById('admin-password-modal').style.display = 'flex';
        }
        
        // 关闭管理员密码验证模态框
        function closeAdminPasswordModal() {
            document.getElementById('admin-password-modal').style.display = 'none';
        }
        
        // 验证管理员密码
        function verifyAdminPassword() {
            const password = document.getElementById('admin-password-input').value;
            const messageElement = document.getElementById('admin-password-message');
            
            if (!password) {
                messageElement.textContent = '请输入管理员密码';
                messageElement.className = 'message message-error';
                messageElement.style.display = 'block';
                return;
            }
            
            // 尝试获取用户数据来验证密码
            fetch('/admin/users', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ password })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    adminPassword = password;
                    isSuperAdmin = data.users.some(u => u.password); // 如果有密码字段返回，说明是超级管理员
                    closeAdminPasswordModal();
                    loadAllUsers();
                } else {
                    messageElement.textContent = data.message || '密码验证失败';
                    messageElement.className = 'message message-error';
                    messageElement.style.display = 'block';
                }
            })
            .catch(error => {
                messageElement.textContent = '网络错误，请重试';
                messageElement.className = 'message message-error';
                messageElement.style.display = 'block';
            });
        }
        
        // 加载所有用户数据
        function loadAllUsers() {
            fetch('/admin/users', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ password: adminPassword })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    allUsers = data.users;
                    document.getElementById('total-users').textContent = allUsers.length;
                    renderUsersTable(allUsers);
                } else {
                    showUserMessage(data.message || '加载用户数据失败', false);
                }
            })
            .catch(error => {
                showUserMessage('网络错误，请重试', false);
            });
        }
        
        // 渲染用户表格
        function renderUsersTable(users) {
            const tableBody = document.getElementById('users-table-body');
            tableBody.innerHTML = '';
            
            const searchName = document.getElementById('search-name').value.toLowerCase();
            const searchPhira = document.getElementById('search-phira').value.toLowerCase();
            const filterAdmin = document.getElementById('filter-admin').value;
            const filterDev = document.getElementById('filter-dev').value;
            
            // 过滤用户
            const filteredUsers = users.filter(user => {
                const nameMatch = user.name.toLowerCase().includes(searchName);
                const phiraMatch = user.phira_id.toLowerCase().includes(searchPhira);
                const adminMatch = filterAdmin === 'all' || user.admin === filterAdmin;
                const devMatch = filterDev === 'all' || user.dev === filterDev;
                
                return nameMatch && phiraMatch && adminMatch && devMatch;
            });
            
            // 填充表格
            filteredUsers.forEach(user => {
                const row = document.createElement('tr');
                row.className = 'user-row';
                row.innerHTML = `
                    <td><input type="checkbox" class="user-select" data-id="${user.id}" /></td>
                    <td>${user.id}</td>
                    <td>${user.name}</td>
                    <td></td>
                    <td>${user.phira_id}</td>
                    <td>${user.phira_name}</td>
                    <td>${user.phira_rks ? parseFloat(user.phira_rks).toFixed(2) : '0.00'}</td>
                    <td>
                        ${user.admin === 'yes' ? '<span class="badge badge-admin">管理员</span>' : ''}
                        ${user.dev === 'yes' ? '<span class="badge badge-dev">开发者</span>' : ''}
                    </td>
                    <td class="actions-cell">
                        <button class="action-btn btn-edit" onclick="openEditModal(${user.id})">编辑</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }
        
        // 打开编辑用户模态框
        function openEditModal(userId) {
            const user = allUsers.find(u => u.id === userId);
            if (!user) return;
            
            document.getElementById('edit-user-id').value = user.id;
            document.getElementById('edit-username').value = user.name;
            document.getElementById('edit-phira-id').value = user.phira_id;
            document.getElementById('edit-admin').value = user.admin;
            document.getElementById('edit-dev').value = user.dev;
            
            // 存储原始密码用于比较
            document.getElementById('password-display').dataset.original = user.password;
            
            document.getElementById('edit-message').style.display = 'none';
            document.getElementById('edit-modal').style.display = 'flex';
        }
        
        // 关闭编辑用户模态框
        function closeEditModal() {
            document.getElementById('edit-modal').style.display = 'none';
        }
        
        // 切换密码显示
        function togglePasswordDisplay() {
            const display = document.getElementById('password-display');
            if (display.textContent === '************') {
                display.textContent = display.dataset.original;
            } else {
                display.textContent = '************';
            }
        }
        
        // 保存用户更改
        function saveUserChanges() {
            const userId = parseInt(document.getElementById('edit-user-id').value);
            const username = document.getElementById('edit-username').value;
            const password = document.getElementById('edit-password').value;
            const phiraId = document.getElementById('edit-phira-id').value;
            const admin = document.getElementById('edit-admin').value;
            const dev = document.getElementById('edit-dev').value;
            
            const changes = {
                name: username,
                admin,
                dev
            };
            
            if (phiraId) changes.phira_id = phiraId;
            if (password) changes.password = password;
            
            fetch('/admin/update', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    password: adminPassword,
                    user_id: userId,
                    changes
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showEditMessage('用户信息更新成功', true);
                    // 重新加载用户数据
                    setTimeout(() => {
                        closeEditModal();
                        loadAllUsers();
                    }, 1500);
                } else {
                    showEditMessage(data.message || '更新失败', false);
                }
            })
            .catch(error => {
                showEditMessage('网络错误，请重试', false);
            });
        }
        
        // 显示编辑消息
        function showEditMessage(message, isSuccess) {
            const messageElement = document.getElementById('edit-message');
            messageElement.textContent = message;
            messageElement.className = `message ${isSuccess ? 'message-success' : 'message-error'}`;
            messageElement.style.display = 'block';
        }
        
        // 显示用户管理消息
        function showUserMessage(message, isSuccess) {
            const messageElement = document.getElementById('user-message');
            messageElement.textContent = message;
            messageElement.className = `message ${isSuccess ? 'message-success' : 'message-error'}`;
            messageElement.style.display = 'block';
            
            // 5秒后隐藏消息
            setTimeout(() => {
                messageElement.style.display = 'none';
            }, 5000);
        }
        
        // 全选用户
        function selectAllUsers() {
            document.querySelectorAll('.user-select').forEach(checkbox => {
                checkbox.checked = true;
            });
        }
        
        // 取消全选
        function deselectAllUsers() {
            document.querySelectorAll('.user-select').forEach(checkbox => {
                checkbox.checked = false;
            });
        }
        
        // 应用批量操作
        function applyBatchAction() {
            const action = document.getElementById('batch-action').value;
            const selectedUserIds = [];
            
            document.querySelectorAll('.user-select:checked').forEach(checkbox => {
                if (checkbox.id !== 'select-all') {
                    selectedUserIds.push(parseInt(checkbox.dataset.id));
                }
            });
            
            if (selectedUserIds.length === 0) {
                showUserMessage('请选择至少一个用户', false);
                return;
            }
            
            // 确定要应用的更改
            let changes = {};
            switch (action) {
                case 'set_admin':
                    changes.admin = 'yes';
                    break;
                case 'remove_admin':
                    changes.admin = 'no';
                    break;
                case 'set_dev':
                    changes.dev = 'yes';
                    break;
                case 'remove_dev':
                    changes.dev = 'no';
                    break;
            }
            
            fetch('/admin/batch-update', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    password: adminPassword,
                    user_ids: selectedUserIds,
                    changes
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 统计成功和失败的数量
                    const successCount = data.results.filter(r => r.status === 'success').length;
                    const errorCount = data.results.filter(r => r.status === 'error').length;
                    
                    if (errorCount === 0) {
                        showUserMessage(`成功更新 ${successCount} 个用户`, true);
                    } else {
                        showUserMessage(`成功更新 ${successCount} 个用户，失败 ${errorCount} 个`, false);
                    }
                    
                    // 重新加载用户数据
                    loadAllUsers();
                } else {
                    showUserMessage(data.message || '批量更新失败', false);
                }
            })
            .catch(error => {
                showUserMessage('网络错误，请重试', false);
            });
        }
        
        // 绑定搜索和过滤事件
        document.getElementById('search-name').addEventListener('input', () => renderUsersTable(allUsers));
        document.getElementById('search-phira').addEventListener('input', () => renderUsersTable(allUsers));
        document.getElementById('filter-admin').addEventListener('change', () => renderUsersTable(allUsers));
        document.getElementById('filter-dev').addEventListener('change', () => renderUsersTable(allUsers));
        
        // 全选/取消全选
        document.getElementById('select-all').addEventListener('change', function() {
            document.querySelectorAll('.user-select').forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    </script>
</body>
</html>